/* 
 * Copyright (c) 2008 Knightsoft
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
*/
package com.knightsoft.util;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Managing and executing a queue of tasks.
 * 
 * @version V1.0 Nov 08, 2008
 * @author Michael
 * @param <R>
 * @param <C>
 */
@SuppressWarnings("serial")
public class TaskManager<R, C extends Callable<R>> extends
		ArrayList<TaskItem<R, C>> {
	private ExecutorService exec = Executors.newSingleThreadExecutor();

	public void add(C task) {
		add(new TaskItem<R, C>(exec.submit(task), task));
	}

	public List<R> getResults() {
		Iterator<TaskItem<R, C>> items = iterator();
		List<R> results = new ArrayList<R>();
		while (items.hasNext()) {
			TaskItem<R, C> item = items.next();
			if (item.future.isDone()) {
				try {
					results.add(item.future.get());
				} catch (Exception e) {
					throw new RuntimeException(e);
				}
				items.remove();
			}
		}
		return results;
	}

	public List<String> purge() {
		Iterator<TaskItem<R, C>> items = iterator();
		List<String> results = new ArrayList<String>();
		while (items.hasNext()) {
			TaskItem<R, C> item = items.next();
			// Leave completed tasks for results reporting:
			if (!item.future.isDone()) {
				results.add("Cancelling " + item.task);
				item.future.cancel(true); // May interrupt
				items.remove();
			}
		}
		return results;
	}
} 
